import { formatCode } from './../codeformat';
import { GeneratorConfig } from '../../model/generator/generatorConfig';
import { camelCase, upperFirst } from 'lodash-es';
import { ColumnType } from '/@/model/generator/tableInfo';
import {
  ComponentConfigModel,
  ComponentOptionModel,
  FrontCodeModel,
} from '/@/model/generator/codeGenerator';
import { QueryConfig } from '/@/model/generator/listConfig';
import { FormProps } from '/@/components/Form';
import { TableInfo } from '/@/components/Designer';
import { camelCaseString } from '/@/utils/event/design';
import { handleAppSearchForm, handleSearchForm } from './exportHelper';
import { PrintButton } from '/@/enums/printEnum';
import { AppFormProps } from '/@/model/generator/appFormConfig';
import { GeneratorAppModel } from '/@/api/system/generator/model';
import { buildAppComponentType, setApiConfig } from './designHelper';

/**
 * 构建代码
 * @param model 配置
 * @param tableInfo 后端数据库表信息
 */
export function buildCode(
  model: GeneratorConfig,
  tableInfo: TableInfo[],
  formProps: FormProps,
): FrontCodeModel {
  const frontCode: FrontCodeModel = {
    listCode: buildListCode(model),
    formCode: buildFormCode(model, tableInfo),
    apiCode: buildApiCode(model, tableInfo),
    modelCode: buildModelCode(model, tableInfo),
    configJsonCode: buildConfigJsonCode(model, formProps),
  };

  console.log('listCode', frontCode.listCode);

  return frontCode;
}

/**
 * 构建代码
 * @param model 配置
 * @param tableInfo 后端数据库表信息
 */
export function buildAppCode(
  model: GeneratorConfig,
  formProps: AppFormProps,
  designType: string,
): GeneratorAppModel {
  const frontCode: GeneratorAppModel = {
    className: model.outputConfig.className,
    outputArea: model.outputConfig.outputArea,
    outputValue: model.outputConfig.outputValue,
    listCode: buildAppListCode(model),
    formCode: buildAppFormCode(model),
    apiCode: buildAppApiCode(model),
    configJsonCode: buildAppConfigJsonCode(model, formProps, designType),
  };

  return frontCode;
}

/**
 * 构建api代码
 * @param model 配置
 */
export function buildApiCode(model: GeneratorConfig, _tableInfo: TableInfo[]): string {
  const className = model.outputConfig.className;
  // const lowerClassName = lowerCase(className);
  const lowerClassName = className?.toLowerCase();
  const pascalClassName = upperFirst(camelCase(className));

  let mainTable;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName));
  const hasSetUserIdButton = hasButton(model.listConfig.buttonConfigs, 'batchSetUserId');
  const hasExportButton = hasButton(model.listConfig.buttonConfigs, 'export');

  const code = `
import { ${pascalMainTableName}Model, ${pascalMainTableName}PageParams, ${pascalMainTableName}PageResult } from './model/${pascalClassName}Model';
import { defHttp } from '/@/utils/http/axios';
import { ErrorMessageMode } from '/#/axios';

enum Api {
  Page = '/${model.outputConfig.outputValue}/${lowerClassName}/page',
  List = '/${model.outputConfig.outputValue}/${lowerClassName}/list',
  Info = '/${model.outputConfig.outputValue}/${lowerClassName}/info',
  ${pascalMainTableName} = '/${model.outputConfig.outputValue}/${lowerClassName}',
  ${
    hasSetUserIdButton
      ? `
  DataAuth = '/${model.outputConfig.outputValue}/${lowerClassName}/data-auth',`
      : ''
  }
  ${
    hasExportButton
      ? `
  Export = '/${model.outputConfig.outputValue}/${lowerClassName}/export',`
      : ''
  }
}

/**
 * @description: 查询${pascalMainTableName}分页列表
 */
export async function get${pascalMainTableName}Page(params: ${pascalMainTableName}PageParams, mode: ErrorMessageMode = 'modal') {
  return defHttp.get<${pascalMainTableName}PageResult>(
    {
      url: Api.Page,
      params,
    },
    {
      errorMessageMode: mode,
    },
  );
}

/**
 * @description: 获取${pascalMainTableName}信息
 */
export async function get${pascalMainTableName}(id: String, mode: ErrorMessageMode = 'modal') {
  return defHttp.get<${pascalMainTableName}Model>(
    {
      url: Api.Info,
      params: { id },
    },
    {
      errorMessageMode: mode,
    },
  );
}

/**
 * @description: 新增${pascalMainTableName}
 */
export async function add${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') {
  return defHttp.post<boolean>(
    {
      url: Api.${pascalMainTableName},
      params: ${camelCaseMainTableName},
    },
    {
      errorMessageMode: mode,
    },
  );
}

/**
 * @description: 更新${pascalMainTableName}
 */
export async function update${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') {
  return defHttp.put<boolean>(
    {
      url: Api.${pascalMainTableName},
      params: ${camelCaseMainTableName},
    },
    {
      errorMessageMode: mode,
    },
  );
}

/**
 * @description: 删除${pascalMainTableName}（批量删除）
 */
export async function delete${pascalMainTableName}(ids: string[], mode: ErrorMessageMode = 'modal') {
  return defHttp.delete<boolean>(
    {
      url: Api.${pascalMainTableName},
      data: ids,
    },
    {
      errorMessageMode: mode,
    },
  );
}

${
  hasSetUserIdButton
    ? `
/**
 * @description: 修改权限${pascalMainTableName}
 */
export async function setDataAuth${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') {
  return defHttp.put<boolean>(
    {
      url: Api.DataAuth,
      params: ${camelCaseMainTableName},
    },
    {
      errorMessageMode: mode,
    },
  );
}
  `
    : ''
}
${
  hasExportButton
    ? `
/**
 * @description: 导出${pascalMainTableName}
 */
export async function export${pascalMainTableName}(
  params?: object, 
  mode: ErrorMessageMode = 'modal'
) {
  return defHttp.download(
    {
      url: Api.Export,
      method: 'GET',
      params,
      responseType: 'blob',
    },
    {
      errorMessageMode: mode,
    },
  );
}
  `
    : ''
}
`;
  return code;
}

/**
 * 构建类型代码
 * @param model 配置
 * @param tableInfo 后端数据库表信息
 */
export function buildModelCode(model: GeneratorConfig, tableInfo: TableInfo[]): string {
  let mainTable;
  let childTables;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
    childTables = model.tableConfigs?.filter((item) => !item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
    childTables = model.tableStructureConfigs?.filter((item) => !item.isMain);
    mainTable.pkField = 'id';
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }
  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCaseMainTableName);

  const code = `
  import { BasicPageParams, BasicFetchResult } from '/@/api/model/baseModel';

${
  model.listConfig.queryConfigs.length > 0
    ? `
/**
* @description: ${pascalMainTableName}分页参数 模型
*/
export interface ${pascalMainTableName}PageParams extends BasicPageParams {
 ${model.listConfig.queryConfigs
   .map((item) => {
     const table = tableInfo?.find((x) => x.isMain); //找到主表信息
     const field = table?.fields.find((x) => x.name === item.fieldName); //找到当前字段信息

     if (field?.type === ColumnType.DATE) {
       return `
 ${camelCaseString(item.fieldName) + 'Start'}: string;
 ${camelCaseString(item.fieldName) + 'End'}: string;`;
     } else {
       return `
 ${camelCaseString(item.fieldName)}: string;`;
     }
   })
   .join('\n')}
}
`
    : `
    /**
    * @description: ${pascalMainTableName}分页参数 模型
    */
   export type ${pascalMainTableName}PageParams = BasicPageParams;
   `
}


/**
 * @description: ${pascalMainTableName}分页返回值模型
 */
export interface ${pascalMainTableName}PageModel {
  ${camelCaseString(mainTable.pkField) + ': string; \n'}
  ${model.listConfig.columnConfigs
    .map((item) => {
      if (item.columnName !== mainTable.pkField) {
        return `
  ${camelCaseString(item.columnName)}: string;`;
      }
    })
    .join('\n')}
}

${
  Array.isArray(tableInfo) &&
  tableInfo.length &&
  model.tableConfigs
    ?.map((item) => {
      const tableNameFirstUpperCase = upperFirst(camelCase(item.tableName));
      //当前遍历的表信息
      const thisTableInfo = tableInfo?.find((table) => table.name === item.tableName);
      const thisTableColumnInfo = thisTableInfo?.fields;
      // 如果是主表 默认需要加入子表的List字段
      if (item.isMain) {
        return `
/**
 * @description: ${tableNameFirstUpperCase}表类型
 */
export interface ${tableNameFirstUpperCase}Model {
  ${thisTableColumnInfo
    ?.map((column) => {
      return `
  ${camelCaseString(column.name)}: ${column.type === ColumnType.NUMBER ? 'number' : 'string'};`;
    })
    .join('\n')}

  ${
    childTables &&
    childTables
      .map((childTable) => {
        const childTablePascalName = upperFirst(camelCaseString(childTable.tableName));
        return `
  ${camelCaseString(childTable.tableName) + 'List?'} : ${childTablePascalName}Model;`;
      })
      .join('\n')
  }
} 
    `;
      } else {
        return `
/**
 * @description: ${tableNameFirstUpperCase}表类型
 */
export interface ${tableNameFirstUpperCase}Model {
  ${thisTableColumnInfo
    ?.map((column) => {
      return `  
  ${camelCaseString(column.name)}: ${column.type === ColumnType.NUMBER ? 'number' : 'string'};`;
    })
    .join('\n')}
} 
    `;
      }
    })
    .join('\n')
}



/**
 * @description: ${pascalMainTableName}分页返回值结构
 */
export type ${pascalMainTableName}PageResult = BasicFetchResult<${pascalMainTableName}PageModel>;
\n
  `;
  return formatCode(code);
}

/**
 * 构建列表页代码
 * @param model 配置
 */
export function buildListCode(model: GeneratorConfig): string {
  const className = model.outputConfig.className;
  const formType = model.formJson.config.formType;
  // const lowerClassName = lowerCase(className);
  const lowerClassName = className?.toLowerCase();
  const pascalClassName = upperFirst(camelCase(className));

  // //是否有左侧菜单
  // const isMenu = model.listConfig.isLeftMenu;
  // //左侧占比
  // const treeFlex = model.listConfig.leftMenuConfig?.leftWidth;
  let mainTable;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
    mainTable.pkField = 'id';
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName));
  const componentArray = [] as string[];

  model.listConfig.columnConfigs.map((config) => {
    componentArray.push(config.componentType!);
  });
  let btnEvent = `{`;
  model.listConfig.buttonConfigs
    .filter((x) => x.isUse && x.isDefault)
    .forEach((x) => {
      btnEvent += `${x.code} : handle${upperFirst(x.code)},`;
    });

  btnEvent += '}';

  const buttonConfigs = model.listConfig.buttonConfigs;
  const hasAddButton = hasButton(buttonConfigs, 'add');
  const hasEditButton = hasButton(buttonConfigs, 'edit');
  const hasRefreshButton = hasButton(buttonConfigs, 'refresh');
  const hasViewButton = hasButton(buttonConfigs, 'view');
  const hasBatchDeleteButton = hasButton(buttonConfigs, 'batchdelete');
  const hasDeleteButton = hasButton(buttonConfigs, 'delete');
  const hasImportButton = hasButton(buttonConfigs, 'import');
  const hasExportButton = hasButton(buttonConfigs, 'export');
  const hasSetUserIdButton = hasButton(buttonConfigs, 'batchSetUserId');
  const hasStartWorkButton = hasButton(buttonConfigs, 'startwork');
  const hasPrintButton = hasButton(buttonConfigs, 'print');
  const hasTemplatePrint = hasButton(buttonConfigs, PrintButton.CODE);
  const isSetDataAuth = model.outputConfig.isDataAuth;

  //判断是否有用到数据源数据字典的组件
  const code = `
<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    ${
      model.listConfig.isLeftMenu
        ? `<div class="w-1/5 xl:w-1/5 mr-2">
      <BasicTree
        title="${model.listConfig.leftMenuConfig?.menuName || ``}"
        toolbar
        search
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="{ key: '${
          model.listConfig.leftMenuConfig?.datasourceType === 'static' ? `key` : `value`
        }', title: '${
            model.listConfig.leftMenuConfig?.datasourceType === 'dic'
              ? `name`
              : model.listConfig.leftMenuConfig?.datasourceType === 'api'
              ? `label`
              : model.listConfig.leftMenuConfig?.showFieldName || `title`
          }' }"
        @select="handleSelect"
      >
        <template #title="item">
        ${
          model.listConfig.leftMenuConfig?.parentIcon
            ? `<template v-if="item.renderIcon === 'parentIcon'">
                <Icon icon="${model.listConfig.leftMenuConfig?.parentIcon}" />
              </template>`
            : ''
        }
        ${
          model.listConfig.leftMenuConfig?.childIcon
            ? `<template v-if="item.renderIcon === 'childIcon'">
                <Icon icon="${model.listConfig.leftMenuConfig?.childIcon}" />
              </template>`
            : ''
        }
          &nbsp;&nbsp;{{ ${
            model.listConfig.leftMenuConfig?.datasourceType === 'dic'
              ? `item.name`
              : model.listConfig.leftMenuConfig?.datasourceType === 'api'
              ? `item.label`
              : `item.${model.listConfig.leftMenuConfig?.showFieldName || 'title'}`
          } }}
        </template>
      </BasicTree>
    </div>`
        : ``
    }
    ${model.listConfig.isLeftMenu ? '<div class="w-4/5 xl:w-4/5">' : ''} 
      <BasicTable @register="registerTable" ${
        hasBatchDeleteButton || hasTemplatePrint || (hasSetUserIdButton && isSetDataAuth)
          ? `:row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"`
          : ''
      }>
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <a-button v-else type="primary">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          ${
            componentArray.includes('switch')
              ? `<template v-if="column.componentType === 'switch'">
                  <a-switch
                    v-model:checked="record[column.dataIndex]"
                    :unCheckedValue="0"
                    :checkedValue="1"
                    :disabled="true"
                  />
                </template>`
              : ''
          }
          ${
            componentArray.includes('picker-color')
              ? `<template v-if="column.componentType === 'picker-color'">
                  <ColorPicker
                    v-model:value="record[column.dataIndex]"
                    :disabled="true"
                  />
                </template>`
              : ''
          }
          ${
            componentArray.includes('money-chinese')
              ? `<template v-if="column.componentType === 'money-chinese'">
                  {{ !isNaN(record[column.dataIndex]) && record[column.dataIndex] !== null ? nzhcn.encodeB(record[column.dataIndex]) + '元' :'' }}
                </template>`
              : ''
          }
          <template v-if="column.dataIndex === 'action'">
            <TableAction :actions="getActions(record)" />
          </template>
        </template>
      </BasicTable>
      ${model.listConfig.isLeftMenu ? '</div>' : ''}
      
  ${
    hasStartWorkButton
      ? `
      <LookProcess
        v-if="visibleLookProcessRef"
        :taskId="taskIdRef"
        :processId="processIdRef"
        @close="visibleLookProcessRef = false"
        :visible="visibleLookProcessRef"
      />
      <LaunchProcess
        v-if="visibleLaunchProcessRef"
        :schemaId="schemaIdRef"
        :form-data="formDataRef"
        :form-id="formIdComputedRef"
        @close="handleCloseLaunch"
      />
      <ApprovalProcess
        v-if="visibleApproveProcessRef"
        :taskId="taskIdRef"
        :processId="processIdRef"
        :schemaId="schemaIdRef"
        @close="handleCloseApproval"
        :visible="visibleApproveProcessRef"
      />`
      : ''
  }
  ${
    hasTemplatePrint
      ? ` <PrintPreview
    v-if="printData.visible"
    :id="printData.id"
    :request-params-configs="printData.requestParamsConfigs"
    :request-body-configs="printData.requestBodyConfigs"
    :request-header-configs="printData.requestHeaderConfigs"
    @close="printData.visible = false"
  />`
      : ''
  }
  ${
    formType === 'modal'
      ? ` <${pascalClassName}Modal @register="registerModal" @success="handleSuccess" />`
      : ` <${pascalClassName}Drawer @register="registerDrawer" @success="handleSuccess" />`
  }
  ${
    hasImportButton
      ? ` <ImportModal @register="registerImportModal" importUrl="/${model.outputConfig.outputValue}/${lowerClassName}/import" @success="handleImportSuccess"/>`
      : ''
  }
  ${
    hasSetUserIdButton && isSetDataAuth
      ? ` <SetRuleUserModal @register="registerRuleUserModal" @success="handleRuleUserSuccess" />`
      : ''
  }
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed,${model.listConfig.isLeftMenu ? 'onMounted,' : ''}${
    hasBatchDeleteButton || hasDeleteButton || (hasSetUserIdButton && !isSetDataAuth)
      ? 'createVNode,'
      : ''
  }${
    model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig?.datasourceType === 'api'
      ? 'getCurrentInstance,'
      : ''
  } 
${hasTemplatePrint ? ' reactive ' : ''}
} from 'vue';
  ${
    hasDeleteButton || hasBatchDeleteButton || (hasSetUserIdButton && !isSetDataAuth)
      ? `
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined${
    hasSetUserIdButton ? ', CloseCircleOutlined' : ''
  } } from '@ant-design/icons-vue';`
      : ''
  }
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { get${pascalMainTableName}Page, delete${pascalMainTableName}${
    hasSetUserIdButton && isSetDataAuth ? `, setDataAuth${pascalMainTableName}` : ''
  }${hasExportButton ? `, export${pascalMainTableName}` : ''}} from '/@/api/${
    model.outputConfig.outputValue
  }/${lowerClassName}';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useRouter } from 'vue-router';
  ${
    hasPrintButton
      ? `
  import { generateTableJson } from '/@/utils/event/design';
  import printJS from 'print-js';`
      : ''
  }
  ${
    hasTemplatePrint
      ? `
		import { getPrintConfigInfo } from '/@/api/system/generator/print';
		import PrintPreview from '/@/views/generator/print/Preview.vue';
    import { get${pascalMainTableName} } from '/@/api/${model.outputConfig.outputValue}/${lowerClassName}';
	  import { PrintButton } from '/@/enums/printEnum';
	  import { InputParamItem } from '/@/components/ApiConfig/src/interface';
    `
      : ''
  }
  ${
    formType === 'modal'
      ? `
  import { useModal } from '/@/components/Modal';`
      : `
  import { useDrawer } from '/@/components/Drawer';`
  }
  ${
    (hasImportButton || (hasSetUserIdButton && isSetDataAuth)) && formType !== 'modal'
      ? `import { useModal } from '/@/components/Modal';`
      : ''
  }
  ${
    hasStartWorkButton
      ? `
  import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
  import LaunchProcess from '/@/views/workflow/task/components/LaunchProcess.vue';
  import ApprovalProcess from '/@/views/workflow/task/components/ApprovalProcess.vue';
  import { getFormExecuteWorkflow } from '/@/api/form/execute';`
      : ''
  }
  ${
    formType === 'modal'
      ? `
  import ${pascalClassName}Modal from './components/${pascalClassName}Modal.vue';
  `
      : `
  import ${pascalClassName}Drawer from './components/${pascalClassName}Drawer.vue';//
  `
  }
  ${
    hasSetUserIdButton && isSetDataAuth
      ? `
  import SetRuleUserModal from '/@/components/Designer/src/components/generateComponent/SetRuleUserModal.vue';`
      : ''
  }
  ${hasImportButton ? `import { ImportModal } from '/@/components/Import';` : ''}
  ${hasExportButton ? `import { downloadByData } from '/@/utils/file/download';` : ''}
  ${
    componentArray.includes('picker-color')
      ? `import { ColorPicker } from '/@/components/ColorPicker';`
      : ''
  }
  ${componentArray.includes('money-chinese') ? `import nzhcn from 'nzh/cn';` : ''}
  import { searchFormSchema, columns } from './components/config';
  ${
    model.listConfig.buttonConfigs.filter((x) => x.isUse).length > 0 ||
    model.listConfig.leftMenuConfig?.childIcon ||
    model.listConfig.leftMenuConfig?.parentIcon
      ? `import Icon from '/@/components/Icon/index';`
      : ``
  }
  ${
    model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig?.datasourceType === 'datasource'
      ? `import { listToTree } from '/@/utils/helper/treeHelper';`
      : ``
  } 
  ${model.listConfig.isLeftMenu ? `import { BasicTree, TreeItem } from '/@/components/Tree';` : ``} 
  ${
    model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig?.datasourceType === 'dic'
      ? `import { getDicDetailList } from '/@/api/system/dic';`
      : ``
  }
  ${
    model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig?.datasourceType === 'datasource'
      ? `import { getDatasourceData } from '/@/api/system/datasource';`
      : ``
  }
  ${
    model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig?.datasourceType === 'api'
      ? `import { apiConfigFunc } from '/@/utils/event/design';`
      : ``
  }
  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth } = usePermission();

  const filterColumns = filterColumnAuth(columns);
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['view', 'edit', 'delete', 'startwork']);
  const buttonConfigs = computed(()=>{
    const list = ${JSON.stringify(model.listConfig.buttonConfigs.filter((x) => x.isUse))}
    return filterButtonAuth(list);
  })

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const btnEvent = ${btnEvent}

  const { currentRoute } = useRouter();
  ${
    hasTemplatePrint
      ? `const printMenuId = computed(() => currentRoute.value.meta.menuId as string);`
      : ''
  }
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);

  ${
    hasStartWorkButton
      ? `
  const visibleLookProcessRef = ref(false);
  const processIdRef = ref('');

  const visibleLaunchProcessRef = ref(false);
  const schemaIdRef = ref('');
  const formDataRef = ref();

  const visibleApproveProcessRef = ref(false);
  const taskIdRef = ref('');`
      : ''
  }
  ${model.listConfig.isLeftMenu ? `const selectId = ref('');` : ``} 
  ${model.listConfig.isLeftMenu ? `const treeData = ref<TreeItem[]>([]);` : ``} 
  ${
    hasBatchDeleteButton || hasTemplatePrint || (hasSetUserIdButton && isSetDataAuth)
      ? `
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);`
      : ''
  }
  ${
    hasSetUserIdButton && isSetDataAuth
      ? `const [registerRuleUserModal, { openModal: openRuleUserModal }] = useModal();`
      : ''
  }
  ${
    formType === 'modal'
      ? `const [registerModal, { openModal }] = useModal();`
      : `const [registerDrawer, { openDrawer }] = useDrawer();`
  }
  ${
    hasImportButton
      ? `const [registerImportModal, { openModal: openImportModal }] = useModal();`
      : ''
  }
  ${
    hasTemplatePrint
      ? `
    // 模板打印 入参参数
    let printData: {
      visible:boolean;
      id: string;
      code:string;
      requestParamsConfigs: Array<InputParamItem>;
      requestHeaderConfigs: Array<InputParamItem>;
      requestBodyConfigs: Array<InputParamItem>;
    
    } = reactive({
      visible:false,
      id: '',
      code:'',
      requestParamsConfigs: [],
      requestHeaderConfigs: [],
      requestBodyConfigs: [],
    });
    `
      : ''
  }  
  const [registerTable, { reload, ${hasPrintButton ? 'getRawDataSource' : ''} }] = useTable({
    title: '${model.listConfig?.listTitle || pascalClassName + '列表'}',
    api: get${pascalMainTableName}Page,
    rowKey: '${camelCaseString(mainTable.pkField)}',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [${
        model.listConfig.queryConfigs
          .filter((item) => {
            return !!item.isDate;
          })
          .map(
            (item) =>
              `['${camelCaseString(item.fieldName)}', ['${
                camelCaseString(item.fieldName) + 'Start'
              }', '${camelCaseString(item.fieldName) + 'End'}'], '${
                item.format || 'YYYY-MM-DD HH:mm:ss'
              } ', true],`,
          )
          .join('\n')
        // 案例数据 ['fieldDatetime', ['fieldDatetimeStart', 'fieldDatetimeEnd'], 'YYYY-MM-DD HH:mm:ss', isString],
      }],
    },
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, PK: '${camelCaseString(
        mainTable.pkField,
      )}' };
    },
    useSearchForm: ${model.listConfig.queryConfigs.length > 0 ? 'true' : 'false'},
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    ${
      (hasSetUserIdButton && isSetDataAuth) || hasBatchDeleteButton || hasTemplatePrint
        ? `customRow,`
        : ''
    }
  });

  function buttonClick(code) {
    ${
      hasTemplatePrint
        ? `if (code.includes(PrintButton.CODE)) {
      printData.code = code;
    }`
        : ''
    }
    btnEvent[code]();
  }
  ${
    hasAddButton
      ? `
  function handleAdd() {
    ${
      formType === 'modal'
        ? `
    openModal(true, {
      isUpdate: false,
    });`
        : ` 
    openDrawer(true, {
      isUpdate: false,
    });`
    }
  }`
      : ''
  }
  ${
    hasEditButton
      ? `
  function handleEdit(record: Recordable) {
    ${
      formType === 'modal'
        ? `
    openModal(true, {
      id: record.${camelCaseString(mainTable.pkField)},
      isUpdate: true,
    });`
        : ` 
    openDrawer(true, {
      id: record.${camelCaseString(mainTable.pkField)},
      isUpdate: true,
    });`
    }
  }`
      : ''
  }
  ${
    hasDeleteButton || hasBatchDeleteButton
      ? `
    ${
      hasDeleteButton
        ? `
  function handleDelete(record: Recordable) {
    deleteList([record.${camelCaseString(mainTable.pkField)}]);
  }`
        : ''
    }
    ${
      hasBatchDeleteButton
        ? `
  function handleBatchdelete() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: 'Tip',
        description: t('请选择需要删除的数据'),
      });
      return;
    }
    //与工作流相关的数据不能进行批量删除
    const cantDelete = selectedRowsData.value.filter((x) => {
      return (
        (x.workflowData?.enabled && x.workflowData?.status) ||
        (!x.workflowData?.enabled && !!x.workflowData?.processId)
      );
    });
    if (cantDelete.length) {
      notification.warning({
        message: 'Tip',
        description: t('含有不能删除的数据'),
      });
      return;
    }
    deleteList(selectedKeys.value);
  }`
        : ''
    }
  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        delete${pascalMainTableName}(ids).then((_) => {
          reload();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }`
      : ''
  }
  ${
    hasPrintButton
      ? `
  async function handlePrint() {
    const dataSource = Array.isArray(getRawDataSource())
      ? getRawDataSource()
      : getRawDataSource().list;
    const json = generateTableJson(filterColumns, dataSource);
    const properties = filterColumns.map((item) => item.title);
    printJS({
      printable: json,
      properties: properties,
      type: 'json',
    });
  }`
      : ''
  }
  ${
    hasTemplatePrint
      ? `
    // 模板打印
		 async function handleTemplateprint() {
		      if (!selectedKeys.value.length) {
		        notification.warning({
		          message: t('提示'),
		          description: t('请选择数据'),
		        });
		        return;
		      }
		      if (selectedKeys.value.length > 1) {
		        notification.warning({
		          message: t('提示'),
		          description: t('只能选择一条数据进行操作'),
		        });
		        return;
		      }
		      let id = selectedKeys.value[0];
		      try {
		        const record = await get${pascalMainTableName}(id);
		        let res = await getPrintConfigInfo(printData.code, printMenuId.value);
            if(res.enabledMark==null){
              notification.warning({
                message: t('提示'),
                description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
              });
              return ;
            }
            if(res.enabledMark==0){
              notification.warning({
                message: t('提示'),
                description: t('找不到打印模板，请联系管理员。'),
              });
              return ;
            }
            printData.id = res.schemaId;
		        if (res.apiConfig) {
		          let json = JSON.parse(res.apiConfig);
		          if (json.requestParamsConfigs && json.requestParamsConfigs.length > 0) {
		            printData.requestParamsConfigs = json.requestParamsConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          if (json.requestHeaderConfigs && json.requestHeaderConfigs.length > 0) {
		            printData.requestHeaderConfigs = json.requestHeaderConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          if (json.requestBodyConfigs && json.requestBodyConfigs.length > 0) {
		            printData.requestBodyConfigs = json.requestBodyConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          printData.visible = true;
		        }else{
              notification.warning({
					        message: t('提示'),
					        description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
					      });
            }
		      } catch (error) {}
		    }
    `
      : ''
  }
  ${
    hasBatchDeleteButton || hasTemplatePrint || (hasSetUserIdButton && isSetDataAuth)
      ? `
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }
  
  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.${camelCaseString(mainTable.pkField)}) >= 0) {
          let index = selectedRowKeys.indexOf(record.${camelCaseString(mainTable.pkField)});
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.${camelCaseString(mainTable.pkField)});
        }
        selectedKeys.value = selectedRowKeys;
      },
    };
  }`
      : ''
  }
  ${
    hasSetUserIdButton
      ? isSetDataAuth
        ? `
  function handleBatchSetUserId() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: 'Tip',
        description: t('请选择需要设置权限的数据'),
      });
      return;
    }
    openRuleUserModal(true, {
      rowKey: '${camelCaseString(mainTable.pkField)}', 
      columns: filterColumns,
      dataSource: selectedRowsData.value,
      setDataAuthApi: setDataAuth${pascalMainTableName}
    });
  }
  
  function handleRuleUserSuccess() {
    selectedKeys.value = [];
    selectedRowsData.value = [];
    reload();
  }`
        : `
  function handleBatchSetUserId() {
    Modal.confirm({
      title: '操作失败',
      icon: createVNode(CloseCircleOutlined, { style: 'color: #ed6f6f' }),
      content: createVNode(
        'div',
        { style: 'color: #999' },
        '当前功能未配置数据权限，请配置后再进行操作。',
      ),
      centered: true,
      okText: '确定',
      cancelText: '取消',
      onOk() {},
      onCancel() {},
    });
  }`
      : ''
  }
  ${
    hasRefreshButton
      ? `
  function handleRefresh() {
    reload();
  }`
      : ''
  }
  function handleSuccess() {
    reload();
  }
  ${
    hasViewButton
      ? `
  function handleView(record: Recordable) {
      ${
        formType === 'modal'
          ? `
    openModal(true, {
      isView: true,
      id: record.${camelCaseString(mainTable.pkField)},
    });`
          : ` 
    openDrawer(true, {
      isView: true,
      id: record.${camelCaseString(mainTable.pkField)},
    });`
      }
  }`
      : ''
  }
  ${
    hasExportButton
      ? `
  async function handleExport() {
    const res = await export${pascalMainTableName}({ isTemplate: false });
    downloadByData(
      res.data,
      '${model.listConfig?.listTitle || pascalClassName}.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  }`
      : ''
  }
  ${
    hasImportButton
      ? `
  function handleImport() {
    openImportModal(true, {
      title: '快速导入',
      downLoadUrl:'/${model.outputConfig.outputValue}/${lowerClassName}/export',
    });
  }
  function handleImportSuccess(){
    reload()
  }`
      : ''
  }
  ${
    model.listConfig.isLeftMenu
      ? `
  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    reload({ searchInfo: { ${camelCaseString(
      model.listConfig.leftMenuConfig!.listFieldName!,
    )}: selectIds[0] } });
  }

  async function fetch() {
    ${
      model.listConfig.leftMenuConfig?.datasourceType === `dic`
        ? `treeData.value = (await getDicDetailList({
      itemId: '${model.listConfig.leftMenuConfig.dictionaryItemId}',
    })) as unknown as TreeItem[];
    `
        : ``
    }
    ${
      model.listConfig.leftMenuConfig?.datasourceType === `static`
        ? `treeData.value = ${JSON.stringify(model.listConfig.leftMenuConfig.staticData)};`
        : ``
    }
    ${
      model.listConfig.leftMenuConfig?.datasourceType === `api`
        ? `treeData.value = (await apiConfigFunc(${JSON.stringify(
            model.listConfig.leftMenuConfig.apiConfig,
          )}, false)) as unknown as TreeItem[];`
        : ``
    }
    ${
      model.listConfig.leftMenuConfig?.datasourceType === `datasource`
        ? `treeData.value = listToTree(await getDatasourceData('${model.listConfig.leftMenuConfig.datasourceId}'), {
      id: '${model.listConfig.leftMenuConfig.relationFieldName}',
      children: 'children',
      pid: '${model.listConfig.leftMenuConfig.parentFiledName}',
    });
    `
        : ``
    }
    ${
      model.listConfig.leftMenuConfig?.childIcon || model.listConfig.leftMenuConfig?.parentIcon
        ? 'addRenderIcon(treeData.value);'
        : ''
    }
  }
  ${
    model.listConfig.leftMenuConfig?.childIcon || model.listConfig.leftMenuConfig?.parentIcon
      ? `
  function addRenderIcon(data) {
    data.map((item) => {
      if (item.children?.length) addRenderIcon(item.children);
      return (item.renderIcon = item.children?.length ? 'parentIcon' : 'childIcon');
    });
  }`
      : ``
  }
  onMounted(() => {
    fetch();
  });
  `
      : ``
  }
  function getActions(record: Recordable):ActionItem[] {
    ${
      hasStartWorkButton
        ? `
    let actionsList: ActionItem[] = [];
    let editAndDelBtn: ActionItem[] = [];
    actionButtonConfig.value?.map((button) => {
      if (button.code === 'view') {
        actionsList.push({
          icon: button?.icon,
          tooltip: button?.name,
          onClick: handleView.bind(null, record),
        });
      }
      if (['edit', 'delete'].includes(button.code)) {
        editAndDelBtn.push({
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
    });
    if (record.workflowData.enabled) {
      //与工作流有关联的表单
      if (record.workflowData.status) {
        //如果是本人需要审批的数据 就会有taskIds  所以需要修改绑定事件
        const act: ActionItem = {};
        if (record.workflowData.taskIds) {
          act.tooltip = '查看流程(待审批)';
          act.icon = 'daishenpi|svg';
          act.onClick = handleApproveProcess.bind(null, record);
        } else {
          act.tooltip =
            '查看流程' + (record.workflowData.status === 'ACTIVE' ? '(审批中)' : '(已完成)');
          act.icon =
            record.workflowData.status === 'ACTIVE' ? 'jinshenpi|svg' : 'shenpiwancheng|svg';
          act.onClick = handleStartwork.bind(null, record);
        }
        actionsList.unshift(act);
      } else {
        actionsList.unshift({
          icon: 'faqishenpi|svg',
          tooltip: '发起审批',
          onClick: handleLaunchProcess.bind(null, record),
        });
        actionsList = actionsList.concat(editAndDelBtn);
      }
    } else {
      if (!record.workflowData.processId) {
        //与工作流没有关联的表单并且在当前页面新增的数据 如选择编辑、删除按钮则加上
        actionsList = actionsList.concat(editAndDelBtn);
      }
    }
    return actionsList;
  }
    `
        : `
    const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
      if (!record.workflowData?.processId) {
        return {
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        };
      } else {
        if (button.code === 'view') {
          return {
            icon: button?.icon,
            tooltip: button?.name,
            onClick: btnEvent[button.code].bind(null, record),
          };
        } else {
          return {};
        }
      }
    });
    return actionsList;
  }`
    }
  ${
    hasStartWorkButton
      ? `
  function handleStartwork(record: Recordable) {
    if (record.workflowData) {
      visibleLookProcessRef.value = true;
      processIdRef.value = record.workflowData.processId;
    }
  }
  async function handleLaunchProcess(record: Recordable) {
    if (record.workflowData) {
      const result = await getFormExecuteWorkflow({
        formId: formIdComputedRef.value,
        id: record['id'],
      });

      visibleLaunchProcessRef.value = true;
      schemaIdRef.value = record.workflowData.schemaId;
      formDataRef.value = result;
    }
  }
  function handleApproveProcess(record: Recordable) {
    visibleApproveProcessRef.value = true;
    schemaIdRef.value = record.workflowData.schemaId;
    processIdRef.value = record.workflowData.processId;
    taskIdRef.value = record.workflowData.taskIds[0];
  }
  function handleCloseLaunch() {
    visibleLaunchProcessRef.value = false;
    reload();
  }
  function handleCloseApproval() {
    visibleApproveProcessRef.value = false;
    reload();
  }
  `
      : ''
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>`;
  return code;
}

/**
 * 构建表单页面
 * @param model
 * @returns {string}
 */
export function buildFormCode(model: GeneratorConfig, _tableInfo: TableInfo[]): string {
  const className = model.outputConfig.className;
  const formType = model.formJson.config.formType;
  const formWidth = model.formJson.config.formWidth;
  // const lowerClassName = lowerCase(className);
  const lowerClassName = className?.toLowerCase();

  const hasEvent = (formEventConfig, eventType?) => {
    const hasApiEvent = formEventConfig?.some((config) => {
      return config.nodeInfo?.processEvent?.some((event) => {
        return event?.operateType === 'api' && event?.operateConfig?.path;
      });
    });
    const hasLiteflowEvent = formEventConfig?.some((config) => {
      return config.nodeInfo?.processEvent?.some((event) => {
        return event?.operateType === 'liteflow' && event?.operateConfig;
      });
    });

    const returnRes =
      eventType === 'api'
        ? hasApiEvent
        : eventType === 'liteflow'
        ? hasLiteflowEvent
        : hasApiEvent || hasLiteflowEvent;

    return returnRes;
  };

  //判断是否有初始化表单事件
  const hasEventCreate = hasEvent(model.formEventConfig[0]);

  //判断是否有获取表单数据事件
  const hasEventGetData = hasEvent(model.formEventConfig[1]);

  //判断是否有加载表单事件
  const hasEventLoad = hasEvent(model.formEventConfig[2]);

  //判断是否有提交表单事件
  const hasEventSubmit = hasEvent(model.formEventConfig[3]);

  //判断是否有表单事件调用Api
  const hasFormEventApi =
    hasEvent(model.formEventConfig[0], 'api') ||
    hasEvent(model.formEventConfig[1], 'api') ||
    hasEvent(model.formEventConfig[2], 'api') ||
    hasEvent(model.formEventConfig[3], 'api');

  //判断是否有表单事件调用规则引擎
  const hasFormEventLiteflow =
    hasEvent(model.formEventConfig[0], 'liteflow') ||
    hasEvent(model.formEventConfig[1], 'liteflow') ||
    hasEvent(model.formEventConfig[2], 'liteflow') ||
    hasEvent(model.formEventConfig[3], 'liteflow');

  let mainTable;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
    mainTable.pkField = 'id';
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName));
  const code = `
<template>
${
  formType === 'modal'
    ? `
    <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" @cancel="handleClose" :paddingRight="15" :bodyStyle="{ minHeight: '400px !important' }">
      <SimpleForm ref="formRef" :formProps="formProps" :formModel="state.formModel"/>
    </BasicModal>`
    : `
    <BasicDrawer showFooter v-bind="$attrs" @register="registerDrawer" :title="getTitle" @ok="handleSubmit" @cancel="handleClose">
      <SimpleForm ref="formRef" :formProps="formProps" :formModel="state.formModel"/>
    </BasicDrawer>`
}
  
</template>
<script lang="ts" setup>
  import { ref, computed, reactive${hasFormEventApi ? ', getCurrentInstance' : ''} } from 'vue';
  ${
    formType === 'modal'
      ? `import { BasicModal, useModalInner } from '/@/components/Modal';`
      : `import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';`
  }
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { add${pascalMainTableName}, get${pascalMainTableName}, update${pascalMainTableName} } from '/@/api/${
    model.outputConfig.outputValue
  }/${lowerClassName}';
  ${hasFormEventLiteflow ? `import { execute } from '/@/api/liteflow';` : ``}
  import { formProps } from './config';
  import { cloneDeep } from 'lodash-es';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  ${hasFormEventApi ? `import { apiConfigFunc } from '/@/utils/event/design';` : ``}

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();
  const { filterFormSchemaAuth } = usePermission();
  const formRef = ref();
  formProps.schemas = filterFormSchemaAuth(formProps.schemas!);
  const state = reactive({
    formModel: {},
    isUpdate: true,
    isView:false,
    rowId: '',
  });

  const { t } = useI18n();
  ${
    formType === 'modal'
      ? `const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.isUpdate = !!data?.isUpdate;
    state.isView = !!data?.isView;

    setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      showCancelBtn: !state.isView,
      showOkBtn: !state.isView,
      canFullscreen: true,
      width: ${formWidth || 800},
    });
    const viewformProps = cloneDeep(formProps);
    setDisabled(viewformProps.schemas);
    formRef.value.setProps(state.isView ? viewformProps : formProps);
    ${hasEventCreate ? 'createFormEvent()' : ''}
    ${hasEventLoad ? 'loadFormEvent()' : ''}

    if (state.isUpdate || state.isView) {
      state.rowId = data.id;
      const record = await get${pascalMainTableName}(data.id);
      formRef.value.setFieldsValue(record);
      ${hasEventGetData ? 'getFormDataEvent()' : ''}
    } else {
      formRef.value.resetFields();
    }
  });`
      : `const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      state.isUpdate = !!data?.isUpdate;
      state.isView = !!data?.isView;

      setDrawerProps({
        destroyOnClose: true,
        maskClosable: false,
        showFooter:!state.isView,
        canFullscreen: true,
        width: ${formWidth || 800},
      });
      const viewformProps = cloneDeep(formProps);
      setDisabled(viewformProps.schemas);
      formRef.value.setProps(state.isView ? viewformProps : formProps);
      ${hasEventCreate ? 'createFormEvent()' : ''}
      ${hasEventLoad ? 'loadFormEvent()' : ''}

      if (state.isUpdate|| state.isView) {
        state.rowId = data.id;
        const record = await get${pascalMainTableName}(data.id);
        formRef.value.setFieldsValue(record);
        ${hasEventGetData ? 'getFormDataEvent()' : ''}
      } else {
        formRef.value.resetFields();
      } 
    });`
  }

  const getTitle = computed(() => (state.isView ? '查看' : !state.isUpdate ? '新增' : '编辑'));

  ${
    hasEventCreate
      ? `//初始化表单
  async function createFormEvent(){
      ${model.formEventConfig[0]
        .map((x) => {
          return x.nodeInfo?.processEvent?.map((config) => {
            if (config.operateType === 'api') {
              return config.operateConfig?.path
                ? `
    await apiConfigFunc(${JSON.stringify(config.operateConfig)}, false, state.formModel)`
                : '';
            } else if (config.operateType === 'liteflow') {
              return config.operateConfig
                ? `
    await execute('${config.operateConfig}', {})`
                : '';
            }
          });
        })
        .join('\n')}
  }`
      : ''
  }

  ${
    hasEventGetData
      ? `//获取表单数据
  async function getFormDataEvent(){
      ${model.formEventConfig[1]
        .map((x) => {
          return x.nodeInfo?.processEvent?.map((config) => {
            if (config.operateType === 'api') {
              return config.operateConfig?.path
                ? `
    await apiConfigFunc(${JSON.stringify(config.operateConfig)}, false, state.formModel)`
                : '';
            } else if (config.operateType === 'liteflow') {
              return config.operateConfig
                ? `
    await execute('${config.operateConfig}', {})`
                : '';
            }
          });
        })
        .join('\n')}
  }`
      : ''
  }

  ${
    hasEventLoad
      ? `//加载表单
  async function loadFormEvent(){
      ${model.formEventConfig[2]
        .map((x) => {
          return x.nodeInfo?.processEvent?.map((config) => {
            if (config.operateType === 'api') {
              return config.operateConfig?.path
                ? `
    await apiConfigFunc(${JSON.stringify(config.operateConfig)}, false, state.formModel)`
                : '';
            } else if (config.operateType === 'liteflow') {
              return config.operateConfig
                ? `
    await execute('${config.operateConfig}', {})`
                : '';
            }
          });
        })
        .join('\n')}
  }`
      : ''
  }

  ${
    hasEventSubmit
      ? `//提交表单
  async function submitFormEvent(){
      ${model.formEventConfig[3]
        .map((x) => {
          return x.nodeInfo?.processEvent?.map((config) => {
            if (config.operateType === 'api') {
              return config.operateConfig?.path
                ? `
    await apiConfigFunc(${JSON.stringify(config.operateConfig)}, false, state.formModel)`
                : '';
            } else if (config.operateType === 'liteflow') {
              return config.operateConfig
                ? `
    await execute('${config.operateConfig}', {})`
                : '';
            }
          });
        })
        .join('\n')}
  }`
      : ''
  }
  function setDisabled(schemas) {
    const layoutComponents = ['tab', 'grid', 'card'];
    schemas?.map((info) => {
      if (layoutComponents.includes(info.type!)) {
        info.children?.map((childInfo) => {
          childInfo.list.map((com) => {
            if (layoutComponents.includes(com.type)) {
              setDisabled(childInfo.list);
            } else {
              com.dynamicDisabled = true;
            }
          });
        });
      } else if (info.type == 'one-for-one') {
        setDisabled(info.componentProps.childSchemas); 
      } else {
        info.dynamicDisabled = true;
      }
    });
  }

  async function handleSubmit() {
    try {
      const values = await formRef.value?.validate();
      //添加隐藏组件
      if (formProps.hiddenComponent?.length) {
        formProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
      ${
        formType === 'modal'
          ? `setModalProps({ confirmLoading: true });`
          : `setDrawerProps({ confirmLoading: true });`
      }
      

      // TODO custom api
      if (!state.isUpdate) {
        //false 新增
        await add${pascalMainTableName}(values);
        notification.success({
          message: 'Tip',
          description: t('新增成功！'),
        }); //提示消息
      } else {
        values.${camelCaseString(mainTable.pkField)} = state.rowId;
        await update${pascalMainTableName}(values);
        notification.success({
          message: 'Tip',
          description: t('修改成功！'),
        }); //提示消息
      }
      ${hasEventSubmit ? 'submitFormEvent()' : ''}
      ${formType === 'modal' ? `closeModal();` : `closeDrawer();`}
      formRef.value.resetFields();
      emit('success');
    } finally {
      ${
        formType === 'modal'
          ? `setModalProps({ confirmLoading: false });`
          : `setDrawerProps({ confirmLoading: false });`
      }
    }
  }
    
  function handleClose() {
    formRef.value.resetFields();
  }
</script>\n
  `;
  return code;
}

/**
 * 构建表单页面FormSchema 与 列表页面BasicColumn
 * @param model
 * @param formSchema
 */
export function buildConfigJsonCode(model: GeneratorConfig, formProps: FormProps): string {
  let mainTable;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
  }

  const findUpload = (component) => {
    const hasSubComponent = ['tab', 'grid', 'card', 'form', 'one-for-one'];
    return component?.some((info) => {
      if (hasSubComponent.includes(info.type!)) {
        if (info.type === 'form') {
          return info.componentProps.columns?.some((childInfo) => {
            return childInfo.componentType === 'Upload';
          });
        } else if (info.type === 'one-for-one') {
          return info.componentProps.childSchemas?.some((childInfo) => {
            if (childInfo.children) {
              return childInfo.children?.some((childSubInfo) => {
                let hasUpload = childSubInfo.list.some((com) => com.type === 'upload');
                if (hasUpload) return true;
                hasUpload = findUpload(childSubInfo.list);
                return hasUpload;
              });
            } else {
              return childInfo.type === 'upload';
            }
          });
        } else {
          return info.children?.some((childInfo) => {
            let hasUpload = childInfo.list.some((com) => com.type === 'upload');
            if (hasUpload) return true;
            hasUpload = findUpload(childInfo.list);
            return hasUpload;
          });
        }
      } else {
        return info.type === 'upload';
      }
    });
  };

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  //将表名转为驼峰命名 首字母小写驼峰
  //将表名转为帕斯卡命名 首字母大写的驼峰

  const code = `
  import { FormProps, FormSchema } from '/@/components/Form';
  import { BasicColumn } from '/@/components/Table';
  ${findUpload(formProps.schemas) ? `import { uploadApi } from '/@/api/sys/upload';` : ''}

  export const searchFormSchema: FormSchema[] = [
    ${model.listConfig.queryConfigs
      .map((item) => {
        const schema = findSchema(formProps.schemas, camelCaseString(item.fieldName));
        const [isNeedTrans, option] = whetherNeedToTransform(item, model.formJson.list);
        return handleSearchForm(option, schema, item, isNeedTrans);
      })
      .join('\n')}
  ];

  export const columns: BasicColumn[] = [
    ${model.listConfig.columnConfigs
      .map((item) => {
        return `
      {
        dataIndex: '${camelCaseString(item.columnName)}',
        title: '${item.label}',
        componentType:'${item.componentType}',
        ${item.alignType ? `align: '${item.alignType}',` : ''}
        ${item.isTotal ? 'total: true,' : ''}
        ${!item.autoWidth && item.columnWidth ? `width:${item.columnWidth},` : ''}
        ${
          item.componentProps?.datasourceType === 'staticData'
            ? `
        customRender: ({ record }) => {
          const staticOptions = ${JSON.stringify(item.componentProps?.staticOptions)};
          return staticOptions.filter((x) => x.value === record.${camelCaseString(
            item.columnName,
          )})[0]?.label;
        },`
            : ''
        }
        sorter: true,
      },
      `;
      })
      .join('\n')}
  ];


  export const formProps: FormProps = ${JSON.stringify(formProps, (key, value) => {
    if (key === 'api') {
      //TODO  后续新增API 这里也要修改
      if (value.toString().includes('uploadApi')) {
        return `#{upload}#`;
      } else {
        return value;
      }
    }
    return value;
  })};\n
  `;
  return formatCode(code.replace(`"#{upload}#"`, 'uploadApi'));
}

/**
 * 构建app 的api代码
 * @param model 配置
 * @param _tableInfo
 * @returns
 */
export function buildAppApiCode(model: GeneratorConfig): string {
  const className = model.outputConfig.className;
  const lowerClassName = className?.toLowerCase();

  let mainTable;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
    mainTable.pkField = 'id';
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName));

  const code = `
import {
  http
} from '@/common/request/index.js'; // 局部引入

const api = {
  Page : '/${model.outputConfig.outputValue}/${lowerClassName}/page',
  List : '/${model.outputConfig.outputValue}/${lowerClassName}/list',
  Info : '/${model.outputConfig.outputValue}/${lowerClassName}/info',
  ${pascalMainTableName} : '/${model.outputConfig.outputValue}/${lowerClassName}'
}

/**
 * 根据参数  查询${pascalMainTableName}分页列表
 * @param {Object} params - 查询参数  
 */
export const get${pascalMainTableName}Page = (params) => {
  return http.get(api.Page, {
    params
  })
}

  
/**
 * 根据参数 查询${pascalMainTableName}列表
 * @param {Object} params - 查询参数  
 */
export const get${pascalMainTableName}List = (params) => {
  return http.get(api.List, {
    params
  })
}

/**
 * 获取${pascalMainTableName}信息
 * @param {Object} params - id  
 */
export const get${pascalMainTableName} = (id) => {
  return http.get(api.Info, {
    params: { id },
  })
}

/**
 * 新增${pascalMainTableName}
 * @param {Object} params - 表单数据  
 */
export const add${pascalMainTableName} = (formData) => {
  return http.post(api.${pascalMainTableName}, formData)
}

/**
 * 修改${pascalMainTableName}
 * @param {Object} params - 表单数据  
 */
export const update${pascalMainTableName} = (formData) => {
  return http.put(api.${pascalMainTableName}, formData)
}

/**
 * 删除${pascalMainTableName}（批量删除）
 * @param {Object} params - 表单数据  
 */
export const delete${pascalMainTableName} = (ids) => {
  return http.delete(api.${pascalMainTableName}, ids)
}
`;
  return code;
}

/**
 * 构建表单页面FormSchema 与 列表页面BasicColumn
 * @param model
 * @param formSchema
 */
export function buildAppConfigJsonCode(
  model: GeneratorConfig,
  formProps: AppFormProps,
  designType: string,
): string {
  const className = model.outputConfig.className;
  // const lowerClassName = lowerCase(className);
  const lowerClassName = className?.toLowerCase();
  // const pascalClassName = upperFirst(camelCase(className));

  let mainTable;
  if (designType == 'data') {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName));
  //将表名转为驼峰命名 首字母小写驼峰
  //将表名转为帕斯卡命名 首字母大写的驼峰

  let categoryConfigs: any = '';
  if (model.listConfig.isLeftMenu) {
    const { datasourceType, listFieldName, childIcon, parentIcon, menuName } =
      model.listConfig.leftMenuConfig!;
    categoryConfigs = {
      datasourceType: datasourceType,
      listFieldName: listFieldName ? camelCaseString(listFieldName) : '',
      childIcon: childIcon,
      parentIcon: parentIcon,
      menuName: menuName,
    };
    if (datasourceType == 'dic') {
      categoryConfigs.dictionaryItemId = model.listConfig.leftMenuConfig?.dictionaryItemId;
    } else if (datasourceType == 'static') {
      categoryConfigs.staticData = model.listConfig.leftMenuConfig?.staticData;
    } else if (datasourceType == 'api') {
      categoryConfigs.apiConfig = setApiConfig(model.listConfig.leftMenuConfig?.apiConfig);
    }
  }

  const code = `
import { 
  get${pascalMainTableName}Page,
  delete${pascalMainTableName} 
} from '@/common/api/${model.outputConfig.outputValue}/${lowerClassName}/index.js';
import {
  componentType,
  datasourceTypeEnum
} from '@/components/simple-form/types/form.js'


export const listProps = {
  rowKey:'${designType == 'data' ? camelCase(mainTable.pkField) : 'id'}',
  //列表请求接口
  api: get${pascalMainTableName}Page,
  // 请求之前处理参数 (params) => {}
  beforeFetch: (params) => {
    for(let key in params){
			if(key.includes(',')){
				delete params[key]
			}
		}
    params.PK='${designType == 'data' ? camelCase(mainTable.pkField) : 'id'}'
		params.FormId='${model.formId}'
    return params
  },
  // 自定义处理接口返回参数
  afterFetch: (data) => {
    return data
  },
  //数据源  静态
  datasource: [],
  //列配置
  columnConfigs: [
    ${model.listConfig.columnConfigs
      .map((item) => {
        return `{
        title: '${item.label}',
        mainField:${item.mainField},
			  showLabel:${item.showLabel},
        componentType:'${buildAppComponentType(item.componentType!)}',
        field: '${camelCaseString(item.columnName)}',
      }`;
      })
      .join(',')}
  ],
  //是否启用搜索
  isSearch: true,
  //是否分页
  isPage: true,
  //分类筛选配置
  categoryConfigs:${JSON.stringify(categoryConfigs)},
  //搜索配置
  searchConfigs: [${model.listConfig.queryConfigs
    .map((item) => {
      const schema = findAppSchema(formProps.schemas, camelCaseString(item.fieldName));

      const [isNeedTrans, option] = whetherNeedToTransform(item, model.formJson.list);
      return handleAppSearchForm(option, schema, item, isNeedTrans);
    })
    .join('\n')}],
  //表单页面地址
  formUrl: '/pages/${model.outputConfig.outputValue}/${lowerClassName}/form',
  //按钮配置
  otherButtons:[${model.listConfig.buttonConfigs
    .filter((item) => item.code !== 'edit' && item.code !== 'delete')
    .map((item) => {
      return `
        {
          text: '${item.name}',
          isUse:${item.isUse},
          code:'${item.code}',
        }`;
    })
    .join(',')}],
  buttonConfigs: [${getButtonConfigs(model.listConfig.buttonConfigs, pascalMainTableName).join(
    ',',
  )}]
}


export const formProps =  ${JSON.stringify(formProps, (key, value) => {
    if (key === 'api') {
      //TODO  后续新增API 这里也要修改
      if (value.toString().includes('uploadApi')) {
        return `#{upload}#`;
      } else {
        return value;
      }
    }
    return value;
  })};\n
`;
  return code.replace(`"#{upload}#"`, 'uploadApi');
}

function getButtonConfigs(buttonConfigs, pascalMainTableName) {
  const codes = ['refresh', 'view', 'add', 'edit', 'delete'];
  const buttons = buttonConfigs.filter((item) => item.isUse);
  const others = buttons.filter((item) => !codes.includes(item.code));
  const temp: any[] = [];
  buttons.forEach((item) => {
    if (item.code === 'edit') {
      temp.push(`{
        code: '${item.code}',
        icon: 'ant-design:edit-square',
        color:'#5E95FF',
        text: '${item.name}',
        action: (record) =>{
          uni.navigateTo({
            url: listProps.formUrl + '?type=edit&id=' + record[listProps.rowKey],
          });
        }
      }`);
    }
    if (item.code === 'delete') {
      temp.push(`{
        code: '${item.code}',
        icon: 'ant-design:delete-outlined',
        color:'#EF6969',
        text: '${item.name}',
        action: async (record, { reload }) => {
          await delete${pascalMainTableName} ([record[listProps.rowKey]]);
          reload()
          //请求删除接口
          uni.showToast({
            title: "删除成功"
          })
        } 
      }`);
    }
  });
  if (others.length > 0) {
    temp.push(`{
      code: 'more',
      icon: 'ant-design:lipsis-outlined',
      color: '#5E95FF',
      text: '更多',
      buttons: ${JSON.stringify(others)},
      action: async (record, { showMoreButton }) => {
        showMoreButton(record[listProps.rowKey])
      },
    }`);
  }
  return temp;
}
/**
 * 构建app列表代码
 * @param model
 */
export function buildAppListCode(_model: GeneratorConfig): string {
  const code = `
<template>
	<SimpleList ref="listRef" :listProps="listProps"></SimpleList>
</template>

<script setup>
import { ref } from 'vue';
import { onReachBottom, onPullDownRefresh,onShow } from '@dcloudio/uni-app'; //不支持onLoad
import SimpleList from '@/components/simple-list/SimpleList.vue';
import { listProps } from './config/index.js'



onReachBottom(() => {
	// 必须要这个事件 可以不写逻辑 
});
const listRef = ref(); 
const firstLoad = ref(true);
onShow(()=>{
	if (firstLoad.value) {
		firstLoad.value = !firstLoad.value;
		return;
	}
	listRef.value.reload();
}) 
</script>

<style></style>

  
  `;
  return code;
}
/**
 * 构建app表单页代码
 * @param model
 * @param _tableInfo
 * @returns
 */
export function buildAppFormCode(model: GeneratorConfig): string {
  const className = model.outputConfig.className;
  // const lowerClassName = lowerCase(className);
  const lowerClassName = className?.toLowerCase();
  // const pascalClassName = upperFirst(camelCase(className));
  let mainTable;
  if (model.tableConfigs && model.tableConfigs.length) {
    //数据优先
    mainTable = model.tableConfigs?.find((item) => item.isMain);
  } else {
    //界面优先、简易模板
    mainTable = model.tableStructureConfigs?.find((item) => item.isMain);
    mainTable.pkField = 'id';
  }

  if (!mainTable) {
    throw new Error('请设置主表');
  }

  const mainTableName = mainTable?.tableName;

  //将表名转为驼峰命名 首字母小写驼峰
  const camelCaseMainTableName = camelCase(mainTableName);
  //将表名转为帕斯卡命名 首字母大写的驼峰
  const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName));
  const code = `
<template>
	<view class="form-fixed">
		<SimpleForm ref="formRef" :formProps="formProps" :disabled="isView"  :control="type"></SimpleForm>
    <view v-if="!isView" class="form-btn-box">
      <button type="default" class="button" @click="reset">重置</button>
      <button type="primary" class="button" @click="submit">确定</button>		
		</view>
	</view>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import SimpleForm from '@/components/simple-form/SimpleForm.vue';
import { formProps } from './config/index.js';
import { onLoad } from '@dcloudio/uni-app'; 
import { add${pascalMainTableName}, update${pascalMainTableName}, get${pascalMainTableName} } from '@/common/api/${model.outputConfig.outputValue}/${lowerClassName}/index.js';
import { listProps } from './config/index.js'
const formRef = ref(); //表单ref
const isUpdate = ref(false); //是否编辑
const isView = ref(false); //是否查看
const id = ref()
const type = ref()
onMounted(async () => {
  //如果是编辑
  if (type.value === 'edit') { 

    const {
      data
    } = await get${pascalMainTableName}(id.value);
    if (data) {
      await formRef.value.setFormData(data);
    }
  }
  //如果是新增
  else if (type.value === 'add') { 
    await formRef.value.init()
  }
  //查看  需要设置为disabled
  else { 
    const {
      data
    } = await get${pascalMainTableName}(id.value);
    if (data) {
      await formRef.value.setFormData(data);
    }
  } 
})

/**
 * 提交
 */
async function submit() {
	try {
		await formRef.value.validate();
    const formData = await formRef.value.getFormData();

		if(isUpdate.value){
      formData[listProps.rowKey]=id.value
			await update${pascalMainTableName}(formData);
			
			uni.showToast({
				title: '修改成功'
			});
		}
		else{
			await add${pascalMainTableName}(formData);
			
			uni.showToast({
				title: '新增成功'
			});
		}


		uni.navigateBack();
	} catch (err) {
		console.log(err);
	}
}

/**
 * 重置
 */
async function reset() {
	await formRef.value.reset();
}


onLoad(async (option) => {
	id.value = option.id;
	type.value = option.type;
  uni.setNavigationBarTitle({
		title: type.value == 'add' ? '新增' : type.value == 'edit' ? '编辑' : '查看'
	})
  //如果是编辑
  if (type.value === 'edit') {
    isUpdate.value = true; 
  }
  //如果是新增
  else if (type.value === 'add') {
    isUpdate.value = false; 
  }
  //查看  需要设置为disabled
  else {
    isView.value = true; 
  } 
});

</script>

<style>
  page{
    background: #fff;
  }
</style>
 
`;
  return code;
}

/**
 * 当前搜索项 是否需要转换
 * @param model 配置
 */
export function whetherNeedToTransform(
  queryConfig: QueryConfig,
  components: ComponentOptionModel[],
): [boolean, ComponentConfigModel | undefined] {
  const layoutComponents = ['tab', 'grid', 'card'];
  let returnTransform: [boolean, ComponentConfigModel | undefined] = [false, undefined];
  components?.some((info) => {
    if (layoutComponents.includes(info.type!)) {
      const hasComponent = info?.layout?.some((childInfo) => {
        const layoutChildOption = childInfo.list.find(
          (com) => com.bindField === queryConfig.fieldName,
        );
        if (!!layoutChildOption) {
          returnTransform = transformComponent.includes(layoutChildOption.type)
            ? [true, layoutChildOption.options]
            : [false, undefined];
          return true;
        }
        if (!childInfo.list.length) return false;
        const transformCom = whetherNeedToTransform(queryConfig, childInfo.list);
        if (!!transformCom) {
          returnTransform = transformCom;
          return true;
        }
        return false;
      });
      return hasComponent;
    } else {
      const option = components.find((item) => item?.bindField === queryConfig.fieldName);
      if (!!option) {
        returnTransform = transformComponent.includes(option.type)
          ? [true, option?.options]
          : [false, undefined];
      }
      return !!option;
    }
  });
  return returnTransform;
}

export function findSchema(schemaArr, fieldName) {
  let schema;
  const formListComponent = ['tab', 'grid', 'card'];
  schemaArr?.some((info) => {
    if (formListComponent.includes(info.type!)) {
      const hasComponent = info.children.some((childInfo) => {
        schema = childInfo.list.find((com) => com.field === fieldName);
        if (!!schema) return true;
        schema = findSchema(childInfo.list, fieldName);
        return !!schema;
      });
      return !!hasComponent;
    } else {
      schema = info.field === fieldName ? info : null;
      return !!schema;
    }
  });
  return schema;
}
export function findAppSchema(schemaArr, fieldName) {
  let schema;
  const formListComponent = ['Tab', 'Segmented', 'Collapse'];
  schemaArr?.some((info) => {
    if (formListComponent.includes(info.component)) {
      const hasComponent = info.layout.some((childInfo) => {
        schema = childInfo.children.find((com) => com.field === fieldName);
        if (!!schema) return true;
        schema = findAppSchema(childInfo.children, fieldName);
        return !!schema;
      });
      return !!hasComponent;
    } else {
      schema = info.field === fieldName ? info : null;
      return !!schema;
    }
  });
  return schema;
}
const hasButton = (list, code) => {
  return list.filter((x) => x.code === code && x.isUse).length > 0;
};

/**
 * 判断是否存在远程组件 使用 数据字典
 * @param components 判断是否存在远程组件 使用 数据字典
 * @param type dic datasource api
 * @returns
 */
// export function existRemoteComponent(components: ComponentOptionModel[], type: string): boolean {
//   const idx = components.findIndex(
//     (item) => transformComponent.includes(item.type) && item.options.datasourceType === type,
//   );
//   if (idx > -1) {
//     return true;
//   }

//   const tabComponents = components.filter((item) => item.type === 'tab');
//   if (tabComponents && tabComponents.length > 0) {
//     let layoutChildOption;
//     for (const tabComp of tabComponents) {
//       if (tabComp.layout) {
//         for (const ly of tabComp.layout) {
//           layoutChildOption = ly.list.find(
//             (item) =>
//               transformComponent.includes(item.type) && item.options.datasourceType === type,
//           );
//           break;
//         }
//       }
//     }
//     if (layoutChildOption && transformComponent.includes(layoutChildOption.type)) {
//       return true;
//     } else {
//       return false;
//     }
//   }

//   const gridComponents = components.filter((item) => item.type === 'grid');
//   if (gridComponents && gridComponents.length > 0) {
//     let layoutChildOption;
//     for (const gridComp of gridComponents) {
//       if (gridComp.layout) {
//         for (const ly of gridComp.layout) {
//           layoutChildOption = ly.list.find(
//             (item) =>
//               transformComponent.includes(item.type) && item.options.datasourceType === type,
//           );
//           break;
//         }
//       }
//     }
//     if (layoutChildOption && transformComponent.includes(layoutChildOption.type)) {
//       return true;
//     } else {
//       return false;
//     }
//   }
//   return false;
// }

//需要转换为非输入框的组件
const transformComponent = [
  'number',
  'radio',
  'checkbox',
  'select',
  'cascader',
  'associate-select',
  'associate-popup',
  'multiple-popup',
  'area',
  'switch',
  'time',
  'date',
  'slider',
  'rate',
  'computational',
  'money-chinese',
  'info',
  'organization',
  'picker-color',
  'user',
];
